package com.poker;

import java.util.ArrayList;
import java.util.List;

import android.app.Activity;
import android.content.pm.ActivityInfo;
import android.os.Bundle;
import android.view.Display;
import android.view.View;
import android.view.ViewGroup;
import android.view.View.OnClickListener;
import android.view.ViewParent;
import android.view.WindowManager;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.RelativeLayout;
import android.widget.RelativeLayout.LayoutParams;

import com.landlords.constants.PokerConstatns;
import com.landlords.model.Poker;
import com.landlords.service.PokerService;
import com.poker.constants.Constants;
import com.poker.ui.MyButton;
import com.poker.ui.MyPokerImageView;

public class DouDizhuActivity extends Activity {
	private MyButton startGame;
	private MyButton reStartGame;
	private MyButton qiangDizhu;
	private MyButton jiaoDizhu;
	private MyButton btnGoCards;
	private MyButton btnPassCards;
	private MyButton btnAlertCards;

	private ImageView computer1Type;
	private ImageView computer2Type;
	private ImageView userType;

	private RelativeLayout userPokerAreas;
	private LinearLayout dipaiArea;

	private List<Poker> pokerList;

	private List<Poker> computer1PokerList;// 电脑一的牌
	private List<Poker> computer2PokerList;// 电脑二的牌
	private List<Poker> userPokerList;// 玩家的牌
	private List<Poker> lastedPokerList;// 选地主可拿的3张底牌

	private List<MyPokerImageView> pokerImageViewCache = new ArrayList<MyPokerImageView>();// 图片的缓存队列，主要为了减少创建view

	private int screenHeight;
	private int screenWidth;

	private int pokerWidth = 35;
	private int commonMarginSpace = 20;
	private int commonTopSpace = 90;

	private PokerService pokerService = new PokerService();

	private static int DIZHU_USER = 0;
	private static int DIZHU_COMPUTER1 = 1;
	private static int DIZHU_COMPUTER2 = 2;

	private int curDizhu = -1;

	@Override
	protected void onStart() {
		WindowManager manage = getWindowManager();
		Display display = manage.getDefaultDisplay();
		screenHeight = display.getHeight();
		screenWidth = display.getWidth();

		super.onStart();
	}

	/** Called when the activity is first created. */
	@Override
	public void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.dizhu);
		// 设置默认为横屏
		setRequestedOrientation(ActivityInfo.SCREEN_ORIENTATION_LANDSCAPE);

		if (pokerList == null) {
			pokerList = new ArrayList<Poker>();
			for (int i = 0; i < PokerConstatns.POKER_TOTAL_COUNT; i++) {
				pokerList.add(PokerConstatns.A_DECK_OF_POKERS.get(i));
			}
		}

		qiangDizhu = (MyButton) findViewById(R.id.qiangDizhu);
		jiaoDizhu = (MyButton) findViewById(R.id.jiaoDizhu);
		btnGoCards = (MyButton) findViewById(R.id.btnGoCards);
		btnPassCards = (MyButton) findViewById(R.id.btnPassCards);
		btnAlertCards = (MyButton) findViewById(R.id.btnAlertCards);
		UserBtnOnClickListener uol = new DouDizhuActivity.UserBtnOnClickListener();
		qiangDizhu.setOnClickListener(uol);
		jiaoDizhu.setOnClickListener(uol);
		btnGoCards.setOnClickListener(uol);
		btnPassCards.setOnClickListener(uol);
		btnAlertCards.setOnClickListener(uol);

		computer1Type = (ImageView) findViewById(R.id.computer1Type);
		computer2Type = (ImageView) findViewById(R.id.computer2Type);
		userType = (ImageView) findViewById(R.id.userType);

		dipaiArea = (LinearLayout) findViewById(R.id.dipaiArea);
		userPokerAreas = (RelativeLayout) findViewById(R.id.userPokerAreas);
		reStartGame = (MyButton) findViewById(R.id.reStartGame);
		startGame = (MyButton) findViewById(R.id.startGame);
		StartGameBtnOnClickListener l = new StartGameBtnOnClickListener();
		startGame.setOnClickListener(l);
		reStartGame.setOnClickListener(l);

	}

	class StartGameBtnOnClickListener implements OnClickListener {

		@Override
		public void onClick(View v) {
			resetToBase();
			dipaiArea.setVisibility(View.VISIBLE);
			pokerList = PokerService.shuffle(pokerList);
			computer1PokerList = new ArrayList<Poker>();
			computer2PokerList = new ArrayList<Poker>();
			userPokerList = new ArrayList<Poker>();
			lastedPokerList = new ArrayList<Poker>();
			for (int i = 0; i < PokerConstatns.POKER_TOTAL_COUNT - 3; i += 3) {
				computer1PokerList.add(pokerList.get(i));
				userPokerList.add(pokerList.get(i + 1));
				computer2PokerList.add(pokerList.get(i + 3));
			}
			lastedPokerList.add(pokerList
					.get(PokerConstatns.POKER_TOTAL_COUNT - 3));
			lastedPokerList.add(pokerList
					.get(PokerConstatns.POKER_TOTAL_COUNT - 2));
			lastedPokerList.add(pokerList
					.get(PokerConstatns.POKER_TOTAL_COUNT - 1));

			PokerService.sortPokerList(userPokerList);

			for (int i = 0; i < lastedPokerList.size(); i++) {
				MyPokerImageView mpi = (MyPokerImageView) dipaiArea
						.getChildAt(i);
				Poker temp = lastedPokerList.get(i);
				mpi.setPoker(temp);
				mpi.setBackgroundDrawable(null);
				mpi.setBackgroundResource(R.drawable.poker);
			}

			for (int i = 0; i < userPokerList.size(); i++) {
				MyPokerImageView myPokerImageView = getPokerImageViewFromCacheOrCreate();
				Poker poker = userPokerList.get(i);
				myPokerImageView.setImageResource(getSourceIdFromPoker(poker));
				myPokerImageView.setPoker(poker);
				userPokerAreas.addView(myPokerImageView);
			}

			resetUserPokers();

			startGame.hideWithGone();
			reStartGame.show();
			jiaoDizhu.show();
		}

	}

	class UserBtnOnClickListener implements OnClickListener {

		@Override
		public void onClick(View v) {
			if (v == qiangDizhu) {

			}
			if (v == jiaoDizhu) {
				jiaoDizhu.hideWithGone();

				for (int i = 0; i < dipaiArea.getChildCount(); i++) {
					MyPokerImageView temp = (MyPokerImageView) dipaiArea
							.getChildAt(i);
					Poker poker = temp.getPoker();
					temp.setBackgroundDrawable(null);
					temp.setBackgroundResource(getSourceIdFromPoker(poker));
					MyPokerImageView myPokerImageView = getPokerImageViewFromCacheOrCreate();

					myPokerImageView.setPoker(poker);
					myPokerImageView
							.setBackgroundResource(getSourceIdFromPoker(myPokerImageView
									.getPoker()));
					userPokerAreas.addView(myPokerImageView);
					userPokerList.add(poker);
				}
				PokerService.sortPokerList(userPokerList);
				resetUserPokers();
				curDizhu = DIZHU_USER;
				resetLogoType();
			}
			if (v == btnGoCards) {

			}
			if (v == btnPassCards) {

			}
			if (v == btnAlertCards) {

			}
		}
	}

	/**
	 * 重置地主和农民类型的logo
	 */
	private void resetLogoType() {
		if (curDizhu >= 0) {
			if (curDizhu == DIZHU_USER) {
				userType.setBackgroundResource(R.drawable.headlogo_type_dizhu);
			} else {
				userType.setBackgroundResource(R.drawable.headlogo_type_nong);
			}

			if (curDizhu == DIZHU_COMPUTER1) {
				computer1Type
						.setBackgroundResource(R.drawable.headlogo_type_dizhu);
			} else {
				computer1Type
						.setBackgroundResource(R.drawable.headlogo_type_nong);
			}

			if (curDizhu == DIZHU_COMPUTER2) {
				computer2Type
						.setBackgroundResource(R.drawable.headlogo_type_dizhu);
			} else {
				computer2Type
						.setBackgroundResource(R.drawable.headlogo_type_nong);
			}
		} else {
			computer1Type.setBackgroundDrawable(null);
			computer2Type.setBackgroundDrawable(null);
			userType.setBackgroundDrawable(null);
		}
	}

	/**
	 * 根据poker的信息，返回在图片中对应的资源id
	 * 
	 * @param poker
	 * @return
	 */
	private int getSourceIdFromPoker(Poker poker) {
		String pokerResource = PokerService.getPokerName(poker);
		return getResources().getIdentifier(
				getPackageName() + ":drawable/" + pokerResource, null, null);
	}

	/**
	 * 重新放置玩家的牌，主要是要重新计算牌的数量以及牌之间的间隔
	 */
	private void resetUserPokers() {
		int totalCount = userPokerAreas.getChildCount();
		int maxX = screenWidth - commonMarginSpace;
		int totalSpace = maxX - pokerWidth;
		int perSpace = totalSpace / totalCount;
		for (int i = totalCount - 1; i >= 0; i--) {
			MyPokerImageView view = (MyPokerImageView) userPokerAreas
					.getChildAt(i);
			view.setBackgroundDrawable(null);
			view.setImageBitmap(null);
			Poker poker = userPokerList.get(i);
			view.setBackgroundResource(getSourceIdFromPoker(poker));
			view.setPoker(poker);
			RelativeLayout.LayoutParams lp = (LayoutParams) view
					.getLayoutParams();
			lp.leftMargin = i * perSpace + commonMarginSpace;
			if (lastedPokerList.contains(poker)) {
				lp.topMargin -= Constants.POKER_UP_DISTANCE;
				view.setClick(true);
			}
		}
	}

	/**
	 * 从缓存中拿取一个MyPokerImageView对象，如果没有则去创建生成一个
	 * 
	 * @return MyPokerImageView
	 */
	private MyPokerImageView getPokerImageViewFromCacheOrCreate() {
		MyPokerImageView temp;
		if (pokerImageViewCache.size() > 0) {
			temp = pokerImageViewCache.get(0);
			pokerImageViewCache.remove(temp);
		} else {
			temp = new MyPokerImageView(DouDizhuActivity.this);
		}
		// 自定义view的布局用，如设置margin属性
		RelativeLayout.LayoutParams commonRp = new RelativeLayout.LayoutParams(
				RelativeLayout.LayoutParams.WRAP_CONTENT,
				RelativeLayout.LayoutParams.WRAP_CONTENT);
		commonRp.setMargins(commonMarginSpace, commonTopSpace, 0, 0);
		temp.setLayoutParams(commonRp);
		temp.setCurX(commonRp.leftMargin);
		// System.out.println(temp.getCurX() + ":" + temp.getCurY());
		return temp;
	}

	/**
	 * 删除一个MyPokerImageView对象，同时把它放入缓存的队列中
	 * 
	 * @param imageView
	 */
	private void removePokerImageView(MyPokerImageView imageView) {
		pokerImageViewCache.add(imageView);
		imageView.removeFromParent();
	}

	/**
	 * 恢复成初始化的布局
	 */
	private void resetToBase() {
		for (int i = 0; i < dipaiArea.getChildCount(); i++) {
			MyPokerImageView mpi = (MyPokerImageView) dipaiArea.getChildAt(i);
			mpi.setBackgroundResource(R.drawable.poker);
			mpi.setPoker(null);
		}
		for (int i = userPokerAreas.getChildCount() - 1; i >= 0; i--) {
			MyPokerImageView mpi = (MyPokerImageView) userPokerAreas
					.getChildAt(i);
			removePokerImageView(mpi);
			System.out.println(mpi.getPoker());
		}
		System.out.println(userPokerAreas.getChildCount());
	}
}